import { useCallback, useState, useRef, useEffect } from 'react';
import { useForm } from '@formily/react';
import { Button, Space, Modal, Popconfirm } from 'antd';
import {
  EditOutlined,
  EyeInvisibleOutlined,
  EyeOutlined,
  MinusCircleOutlined,
} from '@ant-design/icons';
import LibraryConfig, { ILibraryItem, ILibraryRef } from './LibraryConfig';
import { AddIndexLibrary } from './addIndexLibrary'; // 添加索引库
import { TextWidget, getMessage, useCurrentNode } from '@inbiz/react';
import './index.less';

type IIibraryConfig = {
  value?: (ILibraryItem & { isShow?: boolean })[];
  onChange: (value: ILibraryItem[]) => void;
};

function IibraryConfig({ value, onChange }: IIibraryConfig) {

  const { appInfo } = useForm() as unknown as { appInfo: { appId: string } };
  const [addList, $addList] = useState<ILibraryItem[]>([]);
  const [visible, $visible] = useState({ addLibrary: false, libraryConfig: false });
  const libraryRef = useRef<ILibraryRef>(null);

  useEffect(() => {
    $addList([...(value || [])]);
  }, [value]);
  const handleSave = useCallback(
    (list: ILibraryItem[]) => {
      $addList((oldList) => {
        return list.map((item, index) => {
          return {
            ...item,
            selected:
              visible.libraryConfig || oldList?.length
                ? index === list.length - 1
                : index === 0
                  ? true
                  : false,
          };
        });
      });
      $visible({ addLibrary: false, libraryConfig: true });
    },
    [visible],
  );

  const changeAddLibraryMode = useCallback((addLibrary: boolean) => {
    $visible((visible) => ({ ...visible, addLibrary }));
  }, []);
  const handleCancel = useCallback(() => {
    $addList([...(value || [])]);
    $visible({ addLibrary: false, libraryConfig: false });
  }, [value]);
  const handleOk = useCallback(async () => {
    const newValue = await libraryRef.current?.getValue();
    onChange(newValue || []);
    $visible({ addLibrary: false, libraryConfig: false });
  }, [addList]);
  const handelEdit = useCallback(
    (IndexName: string) => {
      $addList((list) => {
        return list.map((item) => ({ ...item, selected: item.IndexName === IndexName }));
      });
      $visible({ addLibrary: false, libraryConfig: true });
    },
    [addList],
  );
  const node = useCurrentNode();
  const handleItemChange = useCallback(
    (IndexName: string, type: 'delete' | 'isShow', isShow?: boolean) => {
      const index = value!.findIndex((item) => item.IndexName === IndexName);
      const newValue = [...value!];
      if (type === 'isShow') {
        newValue[index].isShow = isShow;
      } else {
        newValue.splice(index, 1);
      }
      if (type === 'delete') {
        // 删除插槽中的内容
        const { IndexCode } = value!.find((item) => item.IndexName === IndexName) || {};
        const index = node.children.findIndex(
          (item) => item.props?.['x-component-props']?.IndexCode === IndexCode,
        );
        if (index != -1) {
          node.children.splice(index, 1);
        }
      }
      onChange(newValue);
    },
    [value, onChange],
  );

  // useEffect(() => {
  //   getIndexList({
  //     WebSiteID: appInfo.appId, // 应用id
  //     isOtherSite: true, // 是否是其他应用
  //     pageIndex: 1,
  //     pageSize: 20,
  //     token: getCookie('token')!,
  //     KeyWord: '', // 关键字
  //   }).then((res) => {
  //     if (res.Code == 0 && value?.length>0) {
  //       const newValue = value.filter(item => res.Data.Items.some(ele => ele.IndexName == item.IndexName) )
  //       onChange(newValue)
  //     }
  //   });
  // }, [])
  
  return (
    <div className="dynamc-main-box">
      <div className="dynamc-main">
        {value?.map((item, index) => {
          return (
            <div className="list-item" key={index}>
              <div className="list-item-title">
                {item.IndexType == -1 ? (
                  // 文档单独处理
                  item.IndexName == '_document_'?<TextWidget>{'SearchResultEngine.' + item.IndexDesc}</TextWidget>:
                  <TextWidget>{'SearchResultEngine.' + item.IndexName}</TextWidget>
                ) : (
                  item.IndexName
                )}
              </div>
              <div className="hendle-box">
                <Space>
                  <EditOutlined onClick={() => handelEdit(item.IndexName)} />
                  {item.isShow === false ? (
                    <EyeInvisibleOutlined
                      onClick={() => handleItemChange(item.IndexName, 'isShow', true)}
                    />
                  ) : (
                    <EyeOutlined
                      onClick={() => handleItemChange(item.IndexName, 'isShow', false)}
                    />
                  )}
                  {
                    <Popconfirm
                      placement="left"
                      title={getMessage('SearchResultEngine.areYouSureYouWantToDelete')}
                      onConfirm={() => handleItemChange(item.IndexName, 'delete')}
                      cancelText={getMessage('SearchResultEngine.cancel')}
                      okText={getMessage('SearchResultEngine.determine')}
                    >
                      <MinusCircleOutlined />
                    </Popconfirm>
                  }
                </Space>
              </div>
            </div>
          );
        })}
        <Button
          style={{ marginTop: '10px' }}
          onClick={() => $visible({ addLibrary: true, libraryConfig: false })}
        >
          <TextWidget>SearchResultEngine.addTo</TextWidget>
        </Button>
      </div>
      <Modal
        title={getMessage('SearchResultEngine.configurationParameter')}
        width={1000}
        cancelText={getMessage('SearchResultEngine.cancel')}
        okText={getMessage('SearchResultEngine.determine')}
        visible={visible.libraryConfig}
        destroyOnClose
        onCancel={handleCancel}
        onOk={handleOk}
        zIndex={5}
      >
        <LibraryConfig
          value={addList}
          onChange={$addList}
          appId={appInfo?.appId}
          ref={libraryRef}
          changeAddLibraryMode={changeAddLibraryMode}
        />
      </Modal>
      <AddIndexLibrary
        visible={visible.addLibrary}
        onCancel={() => changeAddLibraryMode(false)}
        onSave={handleSave}
        select={addList}
        appId={appInfo?.appId}
      />
    </div>
  );
}

export default IibraryConfig;
export type IindexIibraryConfig = Exclude<IIibraryConfig['value'], undefined>;
